const multer  = require('@koa/multer')
const COS = require('cos-nodejs-sdk-v5');
var cos = new COS({
    SecretId: 'AKID1rRloa5LK3VhdHfneEWXIm0xd2B3g27v',
    SecretKey: 'Yqrb4HDsHQJvPhiSv8CD4h4A3i7G8k5A',
    Protocol : 'https:'
 });
 let Bucket = 'diancan-1307495908'
 let Region = 'ap-guangzhou'
 let cosfun = function(filename,path){
     return new Promise((resolve,reject)=>{
         cos.uploadFile({
             Bucket,
             Region,
             Key:'diancan/'+filename,
             FilePath:path
         })
         .then(res =>{
            resolve(res.Location)
         })
         .catch(err=>{
            reject(err)
         })
     })
 }
 //二进制上传
 let cosbuffer = function(filename,path){
    return new Promise((resolve,reject)=>{
        cos.putObject({
            Bucket,
            Region,
            Key:'diancan/'+filename,
            Body:Buffer.from(path)
        })
        .then(res =>{
           resolve(res.Location)
        })
        .catch(err=>{
           reject(err)
        })
    })
 }
//配置上传目录和文件名
const storage = multer.diskStorage({
    destination:(req, file, cb) => {
      cb(null, 'upload/img')
    },
    filename: (req, file, cb) => {
        let fileFormat = (file.originalname).split('.')
        let num = `${Date.now()}-${Math.floor(Math.random(0,1)*10000000)}${'.'}${fileFormat[fileFormat.length -1]}`
        cb(null,num)
    }
  })
  
  const upload = multer({ storage: storage })
  module.exports = {upload,cosfun,cosbuffer}
